package com.qige.homework;

import java.util.Arrays;

public class homework4 {
    public static void main(String[] args) {
        MyArrayList list = new MyArrayList();
        list.add("a");
        list.add("b");
        list.add("c");
        list.remove(1);
        list.set(1,"d");
        System.out.println("list.get(1) = " + list.get(1));
        Selector select = list.select();
        while(select.hasNext()){
            Object next = select.next();
            System.out.println(next);
        }
    }
}
interface Selector{
    boolean hasNext();
    Object next();
}
interface Touchable{
    Selector select();
}
class MyArrayList implements Touchable{
    private Object[] all = new Object[2];
    private int total;
    public void add(Object element){
        if (total == all.length){
            all = Arrays.copyOf(all,all.length*2);
        }else {
            all[total++] = element;
        }
    }
    public void remove(int index){
        if (index < 0 || index >= total){
            System.out.println("没有这个元素");
            return;
        }else {
            all[index] = null;
        }
    }
    public void set(int index, Object value){
        if (index < 0 || index >= total){
            System.out.println("没有这个元素");
        }else {
            all[index] = value;
        }
    }
    public Object get(int index){
        if (index < 0 || index >= total){
            System.out.println("没有这个元素");
            return null;
        }else {
            return all[index];
        }
    }
    private class MySelector implements Selector{
        private int cursor;
        @Override
        public boolean hasNext() {
            return cursor != total;
        }

        @Override
        public Object next() {
            return all[cursor++];
        }
    }
    MySelector mySelector = new MySelector();
    @Override
    public Selector select() {
        return mySelector;
    }
}